package com.example.mvc;

import com.example.spring.task.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Demo2Service {

    public  User login(String username)throws Exception{

        User user=null;

       Class.forName("com.mysql.jdbc.Driver");

       Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/student",
               "root",
               "123456");

       String sql="select * from login where username=?";
       PreparedStatement statement = conn.prepareStatement(sql);

       statement.setString(1,username);

       ResultSet rs = statement.executeQuery();

       if (!rs.next()){
           return user;
       }
       user=new User(rs.getString("id"),rs.getString("username"), rs.getNString("password"));


        return user;
    }

    public int register(String username,String password)  {
        int i=0 ;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection conn = DriverManager.getConnection("jdbc:mysql://master:3306/student",
                    "root",
                    "123456");

            String sql="insert into login(username,password) values(?,?)";
            PreparedStatement statement = conn.prepareStatement(sql);

            statement.setString(1,username);
            statement.setString(2,password);

             i= statement.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }
        return i;

    }

}
